package com.easy.dn.ui.main.activity;

import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.easy.common.base.BaseActivity;
import com.easy.common.commonutils.ImageLoaderUtils;
import com.easy.common.commonutils.ShareUtils;
import com.easy.common.commonutils.StringUtils;
import com.easy.common.commonutils.TimeUtil;
import com.easy.common.commonwidget.CustomPopWindow;
import com.easy.common.commonwidget.RippleView;
import com.easy.dn.api.ApiConstants;
import com.easy.dn.bean.ResumeDetailBean;
import com.easy.dn.bean.UserExperienceBean;
import com.easy.dn.ui.main.adapter.WorkExpsAdapter;
import com.easy.dn.ui.main.contract.ResumeDetailContract;
import com.easy.dn.ui.main.model.ResumeDetailModel;
import com.easy.dn.ui.main.presenter.ResumeDetailPresenter;
import com.easy.dn.utils.ContentToPictureUtils;
import com.easy.dn.utils.DnUtils;
import com.easy.dn.utils.MapHelper;
import com.google.android.flexbox.FlexboxLayout;
import com.makeramen.roundedimageview.RoundedImageView;
import com.zhy.android.percent.support.PercentLinearLayout;
import com.zhy.android.percent.support.PercentRelativeLayout;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import dn.easy.com.easyto.R;

import static dn.easy.com.easyto.R.id.getAllResumeBtn;
import static dn.easy.com.easyto.R.id.rv_trade_type;
import static dn.easy.com.easyto.R.id.tv_identity;

/**
 * ░░░░░░░░░░░░░░░░░░░░░░░░▄░░
 * ░░░░░░░░░▐█░░░░░░░░░░░▄▀▒▌░
 * ░░░░░░░░▐▀▒█░░░░░░░░▄▀▒▒▒▐
 * ░░░░░░░▐▄▀▒▒▀▀▀▀▄▄▄▀▒▒▒▒▒▐
 * ░░░░░▄▄▀▒░▒▒▒▒▒▒▒▒▒█▒▒▄█▒▐
 * ░░░▄▀▒▒▒░░░▒▒▒░░░▒▒▒▀██▀▒▌
 * ░░▐▒▒▒▄▄▒▒▒▒░░░▒▒▒▒▒▒▒▀▄▒▒
 * ░░▌░░▌█▀▒▒▒▒▒▄▀█▄▒▒▒▒▒▒▒█▒▐
 * ░▐░░░▒▒▒▒▒▒▒▒▌██▀▒▒░░░▒▒▒▀▄
 * ░▌░▒▄██▄▒▒▒▒▒▒▒▒▒░░░░░░▒▒▒▒
 * ▀▒▀▐▄█▄█▌▄░▀▒▒░░░░░░░░░░▒▒▒
 * 单身狗就这样默默地看着你，一句话也不说。
 * 简历详情
 *
 * @author DN
 * @data 2017/8/8
 **/
public class ResumeDetailActivity extends BaseActivity<ResumeDetailPresenter, ResumeDetailModel> implements ResumeDetailContract.View, RippleView.OnRippleCompleteListener {

    @Bind(R.id.iv_resume_headImg)
    RoundedImageView mIvResumeHeadImg;
    @Bind(R.id.tv_resume_name)
    TextView mTvResumeName;
    @Bind(R.id.tv_refresh_time)
    TextView mTvRefreshTime;
    @Bind(R.id.iv_more)
    RippleView mIvMore;
    @Bind(R.id.iv_video)
    RippleView mIvVideo;
    @Bind(R.id.videoImg)
    ImageView mVideoImg;
    @Bind(R.id.phoneImg)
    ImageView mPhoneImg;
    @Bind(R.id.iv_phone)
    RippleView mIvPhone;
    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.toolbar_layout)
    CollapsingToolbarLayout mToolbarLayout;
    @Bind(R.id.app_bar)
    AppBarLayout mAppBar;
    @Bind(R.id.nestedScrollView)
    NestedScrollView mNestedScrollView;
    @Bind(R.id.resume_chat)
    RippleView mResumeChat;
    @Bind(R.id.resume_collection)
    RippleView mResumeCollection;
    @Bind(R.id.resume_remind)
    RippleView mResumeRemind;
    @Bind(R.id.resume_picture)
    RippleView mResumePicture;
    @Bind(R.id.inviteBtn)
    RippleView mInviteBtn;
    @Bind(getAllResumeBtn)
    RippleView mGetAllResumeBtn;
    @Bind(R.id.percent_relative)
    PercentRelativeLayout mPercentRelative;
    @Bind(R.id.tv_title)
    TextView mTvTitle;
    @Bind(R.id.fl_self_introduction)
    FlexboxLayout mFlSelfIntroduction;
    @Bind(R.id.exp_recyList)
    RecyclerView mRecyclerView;//工作经验
    @Bind(R.id.tv_self_introduction)
    TextView mSeleIntroduction;//自我介紹
    @Bind(R.id.frm_hide_info)
    PercentLinearLayout mFrmHideInfo;
    @Bind(R.id.tv_user_name)
    TextView mTvUserName;
    @Bind(R.id.ll_user_name)
    PercentLinearLayout mLlUserName;
    @Bind(R.id.tv_user_sex)
    TextView mTvUserSex;
    @Bind(R.id.ll_user_sex)
    PercentLinearLayout mLlUserSex;
    @Bind(R.id.tv_user_birthday)
    TextView mTvUserBirthday;
    @Bind(R.id.ll_user_birthday)
    PercentLinearLayout mLlUserBirthday;
    @Bind(R.id.tv_user_liveCity)
    TextView mTvUserLiveCity;
    @Bind(R.id.ll_user_liveCity)
    PercentLinearLayout mLlUserLiveCity;
    @Bind(R.id.tv_response_rate)
    TextView mTvResponseRate;
    @Bind(R.id.tv_professional_rate)
    TextView mTvProfessionalRate;
    @Bind(R.id.tv_about_rate)
    TextView mTvAboutRate;
    @Bind(R.id.tv_appearance_rate)
    TextView mTvAppearanceRate;
    @Bind(R.id.tv_property)
    TextView mTvProperty;
    @Bind(R.id.tv_job_type)
    TextView mTvJobType;
    @Bind(rv_trade_type)
    TextView mRvTradeType;
    @Bind(R.id.tv_district)
    TextView mTvDistrict;
    @Bind(R.id.tv_salary)
    TextView mTvSalary;
    @Bind(R.id.tv_arrival_time)
    TextView mTvArrivalTime;
    @Bind(R.id.tv_exceptional_case)
    TextView mTvExceptionalCase;
    @Bind(tv_identity)
    TextView mTvIdentity;
    @Bind(R.id.view)
    View mView;
    @Bind(R.id.textView10)
    TextView mTextView10;
    @Bind(R.id.fl_proficient)
    FlexboxLayout mFlProficient;
    @Bind(R.id.fl_practised)
    FlexboxLayout mFlPractised;
    @Bind(R.id.fl_commonly)
    FlexboxLayout mFlCommonly;
    private boolean isBottomShow = true;
    private CollapsingToolbarLayoutState state;
    private String mResumeName = "";
    private List<UserExperienceBean> mExpsList = new ArrayList<>();
    private LinearLayoutManager mLayoutManager;
    private ResumeDetailBean resumeDetailBean;
    private CustomPopWindow mCustomPopWindow;

    private enum CollapsingToolbarLayoutState {
        EXPANDED,
        COLLAPSED,
        INTERNEDIATE
    }

    @Override
    public int getLayoutId() {
        return R.layout.act_resume_detail;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public void initView() {
        loadData();
        mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setNestedScrollingEnabled(false);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    finishAfterTransition();
                } else {
                    finish();
                }
            }
        });
        mNestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (scrollY - oldScrollY > 0 && isBottomShow) {  //下移隐藏
                    isBottomShow = false;
                    mPercentRelative.animate().translationY(mPercentRelative.getHeight());
                } else if (scrollY - oldScrollY < 0 && !isBottomShow) {    //上移出现
                    isBottomShow = true;
                    mPercentRelative.animate().translationY(0);
                }
            }
        });
        mAppBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
                                               /**
                                                *  监听appbar的滑动状态
                                                * @param appBarLayout
                                                * @param verticalOffset  <0表示向上滑动
                                                */
                                               @Override
                                               public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                                                   if (verticalOffset == 0) {
                                                       // 展开的状态
                                                       if (state != CollapsingToolbarLayoutState.EXPANDED) {
                                                           state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                                                           mToolbarLayout.setTitle("");//设置title
                                                           mTvTitle.setText("");//设置title不显示
                                                           if (!isBottomShow) {
                                                               isBottomShow = true;
                                                               mPercentRelative.animate().translationY(0);
                                                           }
                                                       }
                                                   } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                                                       //滑动结束之后
                                                       if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                                                           mTvTitle.setText(mResumeName);//设置title不显示
                                                           state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                                                           if (isBottomShow) {
                                                               isBottomShow = false;
                                                               mPercentRelative.animate().translationY(mPercentRelative.getHeight());
                                                           }

                                                       }
                                                   } else {
                                                       if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                                                           // 滑动过程中 中间的状态
                                                           if (state == CollapsingToolbarLayoutState.COLLAPSED) {
                                                           }
                                                           mToolbarLayout.setTitle("");//设置title为INTERNEDIATE
                                                           state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                                                       }
                                                   }
                                               }
                                           }
        );
        mIvMore.setOnRippleCompleteListener(this);
        mIvVideo.setOnRippleCompleteListener(this);
        mIvPhone.setOnRippleCompleteListener(this);
        mResumeChat.setOnRippleCompleteListener(this);
        mResumeCollection.setOnRippleCompleteListener(this);
        mResumeRemind.setOnRippleCompleteListener(this);
        mResumePicture.setOnRippleCompleteListener(this);
        mInviteBtn.setOnRippleCompleteListener(this);
        mGetAllResumeBtn.setOnRippleCompleteListener(this);
    }

    private void loadData() {
        Bundle bundle = getIntent().getExtras();
        Map<String, String> map = MapHelper.getAccessMap();
        map.put("resumeId", bundle.getString("resumeID") == null ? "" : bundle.getString("resumeID"));
        map.put("uid", bundle.getString("uid") == null ? "" : bundle.getString("uid"));
        map.put("jobCoreId", bundle.getString("jobCoreId") == null ? "" : bundle.getString("jobCoreId"));
        mPresenter.getData(map);
    }

    @Override
    public void returnResumeDetailDta(ResumeDetailBean resumeDetailBean) {
        this.resumeDetailBean = resumeDetailBean;
        initData();
    }

    //是否可以与这个求职者对话
    @Override
    public void returnIsChat(Boolean isChat) {
        if (isChat) {
            if (DnUtils.getLocale()) {
                Toast.makeText(this, "对方目前不接受聊天信息。", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "This user has turned off the chat function.", Toast.LENGTH_SHORT).show();
            }
        } else
            showShortToast("聊聊呗");
    }

    // 显示数据
    private void initData() {
        //并没有区分公开简历完整 太墨迹了
//        mTvUserName.setText(resumeDetailBean.getName());
//        mTvUserSex.setText(resumeDetailBean.getSex());
//        mTvUserBirthday.setText(TimeUtil.formatData(TimeUtil.dateFormatYMD, resumeDetailBean.getBirthday()));
        //视频简历
        String videoPath = resumeDetailBean.getVideoPath();
        if (StringUtils.isEmpty(videoPath)) {
            mVideoImg.setImageResource(R.drawable.resume_detail_video_none_icon);
            mIvVideo.setEnabled(false);
        } else {
            mVideoImg.setImageResource(R.drawable.resume_detail_video_icon);
            mIvVideo.setEnabled(true);
        }
        //拨打电话  。。这个东西有毒 先不写

        //工作性質
        mTvProperty.setText(resumeDetailBean.getPropertyStr());
        //期望职位
        mTvJobType.setText(resumeDetailBean.getJobTypeStr());
        //期望行业
        mRvTradeType.setText(resumeDetailBean.getTradeStr());
        //期望地点
        mTvDistrict.setText(resumeDetailBean.getAddressStr());
        //期望月薪
        if (0 != resumeDetailBean.getSalaryBegin() && 0 != resumeDetailBean.getSalaryEnd()) {
            mTvSalary.setText(resumeDetailBean.getSalaryBegin() + "-" + resumeDetailBean.getSalaryEnd() + getResources().getString(R.string.yuan));
        } else {
            mTvSalary.setText(R.string.chat_face);
        }
        // 到岗时间
        if (null != resumeDetailBean.getArrivalTime()) {
            mTvArrivalTime.setText(resumeDetailBean.getArrivalTime() + getResources().getString(R.string.month_detail));
        } else {
            mTvArrivalTime.setText("");
        }
        // 特殊情况
        mTvExceptionalCase.setText(resumeDetailBean.getExceptionalStr());
        // 身份
        mTvIdentity.setText(resumeDetailBean.getUserTypeStr());
        //头像
        ImageLoaderUtils.display(this, mIvResumeHeadImg, ApiConstants.URL + resumeDetailBean.getImgPath(), R.drawable.default_head, R.drawable.default_head);
        //简历名称
        mResumeName = resumeDetailBean.getResumeName();
        mTvResumeName.setText(mResumeName == null ? "" : mResumeName);
        //刷新时间
        mTvRefreshTime.setText(mContext.getResources().getString(R.string.update_time) + " " + TimeUtil.formatData(TimeUtil.dateFormatYMD, resumeDetailBean.getRefreshTime()));
        //自我介绍
        String selfIntroduction = resumeDetailBean.getWordTextZH();
        showlabel(mFlSelfIntroduction, selfIntroduction);
        mSeleIntroduction.setText(resumeDetailBean.getSelfIntroduction());

        // 工作经验
        if (resumeDetailBean.getExps() != null) {
            mExpsList = resumeDetailBean.getExps();
            WorkExpsAdapter workExpsAdapter = new WorkExpsAdapter(R.layout.item_work_exps, mExpsList);
            mRecyclerView.setAdapter(workExpsAdapter);
        }
        //语言
        // -->精通
        String professionalLanguage = resumeDetailBean.getLanguageProfessional();
        showlabel(mFlProficient, professionalLanguage);
        // -->熟练
        String goodLanguage = resumeDetailBean.getLanguageGood();
        showlabel(mFlPractised, goodLanguage);
        // -->一般
        String normalLanguage = resumeDetailBean.getLanguageNormal();
        showlabel(mFlCommonly, normalLanguage);
    }

    /**
     * 显示标签
     *
     * @param flexboxLayout FlexboxLayout
     * @param str           “聪明，强，无敌” --> 以 ，隔开的字符串
     */
    private void showlabel(FlexboxLayout flexboxLayout, String str) {
        if (!StringUtils.isEmpty(str)) {
            String[] allStr = str.split(",");
            for (int i = 0; i < allStr.length; i++) {
                TextView textView = new TextView(mContext);
                textView.setText(allStr[i]);
                textView.setGravity(Gravity.CENTER);
                textView.setTextSize(13);
                textView.setBackgroundResource(R.drawable.resume_detail_label_bg);
                flexboxLayout.addView(textView);
                ViewGroup.LayoutParams params = textView.getLayoutParams();
                if (params instanceof FlexboxLayout.LayoutParams) {
                    FlexboxLayout.LayoutParams layoutParams = (FlexboxLayout.LayoutParams) params;
                    layoutParams.setMargins(10, 10, 0, 0);
                    textView.setLayoutParams(layoutParams);
                }
            }
        }
    }

    @Override
    public void onComplete(RippleView rippleView) {
        switch (rippleView.getId()) {
            case R.id.iv_more:
                //更多  下载+分享
                showPopTopWithDarkBg();
                break;
            case R.id.iv_video:
                //视频简历
                showShortToast("视频简历");
                break;
            case R.id.iv_phone:
                //拨打电话
                showShortToast("拨打电话");
                break;
            case R.id.resume_chat:
                //聊天
                Map<String, String> maps = MapHelper.getAccessMap();
                maps.put("userIMName", resumeDetailBean.getImUserName());
                mPresenter.getIsChatData(maps);
                break;
            case R.id.resume_collection:
                //收藏
                showShortToast("收藏");
                break;
            case R.id.resume_remind:
                //备注
                startActivity(RemarksActivity.class);
                break;
            case R.id.resume_picture:
                // 截图
                ContentToPictureUtils.scrollviewContentToPng(mContext, mNestedScrollView);
                break;
            case R.id.inviteBtn:
                // 面试邀请
                showShortToast("面试邀请");
                break;
            case getAllResumeBtn:
                // 求全简历
                showShortToast("求全简历");
                break;
        }
    }

    /**
     * 显示PopupWindow 同时背景变暗
     */
    private void showPopTopWithDarkBg() {
        View contentView = LayoutInflater.from(this).inflate(R.layout.pop_menu, null);
        //处理popWindow 显示内容
        handleLogic(contentView);
        //创建并显示popWindow
        //弹出popWindow时，背景是否变暗
        // 控制亮度
        mCustomPopWindow = new CustomPopWindow.PopupWindowBuilder(this)
                .setView(contentView)
                .setAnimationStyle(R.style.CustomPopWindowStyle)
                .enableBackgroundDark(true) //弹出popWindow时，背景是否变暗
                .setBgDarkAlpha(0.5f) // 控制亮度
                .setOnDissmissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        Log.e("TAG", "onDismiss");
                    }
                })
                .create()
                .showAsDropDown(mIvMore, 0, 30);
    }

    /**
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
                switch (v.getId()) {
                    case R.id.resume_detail_down:
                        break;
                    case R.id.resume_detail_share:
                        //分享 地址没填
                        ShareUtils.easyShowShare(mContext, "", "", "", "");
                        break;
                }
            }
        };
        contentView.findViewById(R.id.resume_detail_down).setOnClickListener(listener);
        contentView.findViewById(R.id.resume_detail_share).setOnClickListener(listener);
    }

    @Override
    public void showLoading(String title) {

    }

    @Override
    public void stopLoading() {

    }

    @Override
    public void showErrorTip(String msg) {
        showShortToast(msg);
    }

}
